<template>
  <div>
    <el-button type="primary" size="small" style="margin-left: 3px" @click="addNewReg()">
      <el-icon>
        <Edit/>
      </el-icon> &nbsp;挂号
    </el-button>

    <el-button type="primary" size="small" style="margin-left: 3px" @click="clear()">
      <el-icon>
        <Refresh/>
      </el-icon>&nbsp;清空
    </el-button>

    <br><br>
    <div style="font-size:15px;font-family:'Microsoft YaHei'">挂号信息</div>&nbsp;
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">病 历 号 :</span>&nbsp;
          <el-input placeholder="输入病历号" style="width: 110px" again="left" size="small"
                    v-model="formData.caseNumber"
                    @blur="checkCaseNumber()">
          </el-input>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</span>&nbsp;
          <el-input placeholder="输入姓名" style="width: 110px" again="left" size="small"
                    v-model="formData.patientName">
          </el-input>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>&nbsp;
          <el-select placeholder="选择性别" style="width: 110px" size="small" v-model="formData.gender">
            <el-option
                v-for="item in genderOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;龄:</span>&nbsp;
          <el-input placeholder="输入年龄" style="width: 110px" again="left" size="small" v-model="formData.age">
          </el-input>
          <span style="color:red">*</span>
          <el-select placeholder="选择单位" style="width: 110px" size="small" v-model="formData.ageType">
            <el-option label="岁" value="岁"></el-option>
            <el-option label="月" value="月"></el-option>
            <el-option label="天" value="天"></el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="2">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="font-size:13px;font-family:'Microsoft YaHei'">出生日期:</span>
          <el-date-picker
              @change="calculateAge"
              v-model="formData.birthDate"
              type="date"
              placeholder="出生日期" size="small" style="width: 124px" value-format="YYYY-MM-DD">
          </el-date-picker>
        </div>
      </el-col>

      <el-col :span="7">
        <div class="grid-content bg-purple">
          <span style="font-size:13px;font-family:'Microsoft YaHei'">身份证号:</span>&nbsp;&nbsp;&nbsp;
          <el-input placeholder="在此输入身份证号" style="width: 230px" size="small"
                    v-model="formData.idNumber"></el-input>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="grid-content bg-purple">
          <span style="font-size:13px;font-family:'Microsoft YaHei'">家庭住址:</span>&nbsp;
          <el-input placeholder="在此输入家庭住址" style="width: 250px" again="left" size="small"
                    v-model="formData.address">
          </el-input>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="2">
      <el-col :span="4">
  <div class="grid-content bg-purple">
    <span style="color:red">*</span>
    <span style="font-size:13px;font-family:'Microsoft YaHei'">结算类别:</span>&nbsp;
    <el-select 
      placeholder="结算类别" 
      style="width: 100px" 
      size="small" 
      v-model="formData.settlementTypeId"
    >
      <el-option
        v-for="item in settlementTypes"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>
  </div>
</el-col>
      <el-col :span="5">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">看诊日期:
            <el-date-picker
                v-model="formData.visitDate"
                type="date"
                placeholder="看诊日期" size="small" style="width: 125px" value-format="YYYY-MM-DD"
                @change="handleVisitDateChange()">
            </el-date-picker>
          </span>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">午别:</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <el-select placeholder="午别" style="width: 90px" size="small" v-model="formData.timePeriod"
                     @change="handleTimePeriodChange()">
            <el-option
                v-for="item in timePeriodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">挂号科室:</span>&nbsp;
          <el-select placeholder="挂号科室" style="width: 108px" size="small" v-model="formData.departmentId"
                     @change="handleDepartmentChange()">
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="2">
      <el-col :span="4">
  <div class="grid-content bg-purple">
    <span style="color:red">*</span>
    <span style="font-size:13px;font-family:'Microsoft YaHei'">号&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>&nbsp;
    <el-select 
      placeholder="号别" 
      style="width: 100px" 
      size="small" 
      v-model="formData.registrationLevelId"
      @change="handleRegistrationLevelChange()"
    >
      <el-option
        v-for="item in registrationLevels"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>
  </div>
</el-col>

      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">看诊医生:</span>
          <el-select placeholder="看诊医生" style="width: 110px" size="small" v-model="formData.doctorId"
                     @change="handleDoctorChange()">
            <el-option
                v-for="item in doctors"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
               >
          
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="2">
      <el-col :span="4">
        <div>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">病历本</span>
          <input type="checkbox" name="" v-model="formData.needMedicalRecord" true-value="Y" false-value="N"
                 @change="handleMedicalRecordChange()"/>
        </div>
      </el-col>

      <el-col :span="4">
        <div>
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">应收金额:</span>&nbsp;
          <el-input placeholder="应收金额" style="width: 100px" again="left" size="small" :value="registrationFee"
                    readonly>
          </el-input>
        </div>
      </el-col>

      <el-col :span="4">
  <div>
    <span style="color:red">*</span>
    <span style="font-size:13px;font-family:'Microsoft YaHei'">收费方式:</span>&nbsp;
    <el-select 
      placeholder="收费方式" 
      style="width: 100px" 
      size="small" 
      v-model="formData.paymentType"
    >
      <el-option
        v-for="item in paymentTypes"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
  </div>
</el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'
import { useUserStore } from "@/stores/counter.js"
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
console.log('当前存储的用户数据:', localStorage.getItem('user'))
const router = useRouter()
const userStore = useUserStore();
console.log(userStore.id);
const loading = ref(false)
const paymentTypes = ref([
  { value: '51', label: '现金' },
  { value: '52', label: '微信支付' },
  { value: '53', label: '支付宝' },
  { value: '54', label: '银行卡' }
])
// 表单数据
const formData = ref({
  caseNumber: '',                  // 病历号
  patientName: '',                 // 患者姓名
  gender: null,                    // 性别ID
  age: null,                       // 年龄
  ageType: '岁',                   // 年龄类型
  birthDate: null,                 // 出生日期
  idNumber: '',                    // 身份证号
  address: '',                     // 家庭住址
  settlementTypeId: null,          // 结算类别ID
  visitDate: dayjs().format('YYYY-MM-DD'), // 看诊日期
  timePeriod: '上午',              // 午别
  departmentId: null,              // 挂号科室ID
  doctorId: null,                  // 看诊医生ID
  registrationLevelId: null,       // 号别ID
  needMedicalRecord: 'Y',          // 是否需要病历本
  paymentType: null,               // 收费方式
  registrationTime: null,          // 挂号时间
  registrarId: null,               // 挂号员ID
  visitStatus: 1                   // 看诊状态
})

// 生成病历号
function generateCaseNumber() {
  const datePart = dayjs().format('YYYYMMDD')
  const timePart = dayjs().format('HHmmss')
  const randomPart = Math.floor(100 + Math.random() * 900).toString().padStart(3, '0')
  return `${datePart}${timePart}${randomPart}`
}

// 获取默认午别
function getDefaultTimePeriod() {
  const hours = new Date().getHours()
  return hours >= 9 && hours < 12 ? '上午' : '下午'
}

// 下拉选项数据
const genderOptions = ref([])
const departments = ref([])
const doctors = ref([])
const settlementTypes = ref([])
const timePeriodOptions = ref([{ value: '上午', label: '上午' }, { value: '下午', label: '下午' }])
const registrationLevels = ref([])

// 计算属性：挂号费
const registrationFee = computed(() => {
  if (!formData.value.registrationLevelId) return 0
  const level = registrationLevels.value.find(item => item.id === formData.value.registrationLevelId)
  return level ? level.fee : 0
})

// 检查病历号
const checkCaseNumber = async () => {
  const caseNumber = formData.value.caseNumber
  if (!caseNumber) return
  
  try {
    // 修改为只请求一个接口，因为后端已经合并了检查病历号和获取患者信息的功能
    const registrationData = await service.get(`/registration/checkCaseNumber?caseNumber=${caseNumber}`)
    
    if (registrationData) {
      formData.value = {
        ...formData.value,
        patientName: registrationData.patientName || '',
        gender: registrationData.gender || null,
        birthDate: registrationData.birthDate || null,
        idNumber: registrationData.idNumber || '',
        address: registrationData.address || ''
      }
      
      if (formData.value.birthDate) {
        calculateAge()
      }
      
      ElMessage.success('患者信息已自动填充')
    } else {
      ElMessage.warning('未找到该病历号对应的患者信息')
    }
  } catch (error) {
    console.error('检查病历号失败:', error)
    ElMessage.error('检查病历号失败: ' + (error.message || '服务不可用'))
  }
}
// 添加挂号
const addNewReg = async () => {
  try {
    // 表单验证
    if (!validateForm()) {
      return
    }
    // 获取用户store实例
    const userStore = useUserStore()
    
    // 确保用户已登录并获取用户信息
    try {
      const currentUser = userStore.ensureAuthenticated()
      if (!currentUser.id) {
        throw new Error('用户ID不存在')
      }
    } catch (error) {
      ElMessage.error(error.message || '请先登录系统')
      return
    }
    // 准备提交数据
    const registrationData = {
      ...formData.value,
      registrarId: userStore.id, // 设置挂号员ID
      registrationTime: new Date(), // 设置挂号时间
      visitStatus: 1 // 设置看诊状态为1
    }
    
    // 调用后端API
    loading.value = true
    const response = await service.post('/registration/add', registrationData)
    
    if (response) {
      ElMessage.success('挂号成功!')
      
      // 打印挂号信息
      printRegistrationInfo(registrationData)
      
      // 重置表单(保留部分字段)
      formData.value = {
        ...clear(), // 使用clear函数重置基本字段
        settlementTypeId: formData.value.settlementTypeId, // 保留结算类型
        paymentType: formData.value.paymentType // 保留支付方式
      }
    } else {
      ElMessage.error(response?.message || '挂号失败，请重试')
    }
  } catch (error) {
    console.error('挂号出错:', error)
    ElMessage.error('挂号出错: ' + (error.message || '服务不可用'))
  } finally {
    loading.value = false
  }
}

// 打印挂号信息
const printRegistrationInfo = (registration) => {
  const info = {
    '病历号': registration.caseNumber,
    '患者姓名': registration.patientName,
    '挂号级别': registrationLevels.value.find(l => l.id === registration.registrationLevelId)?.name || '',
    '挂号费': registrationFee.value,
    '看诊日期': registration.visitDate,
    '午别': registration.timePeriod,
    '科室': departments.value.find(d => d.id === registration.departmentId)?.name || '',
    '医生': doctors.value.find(d => d.id === registration.doctorId)?.realName || ''
  }
  console.log('挂号信息:', info)
}

// 清空表单
const clear = () => {
  formData.value = {
    caseNumber: generateCaseNumber(),
    patientName: '',
    gender: null,
    age: null,
    ageType: '岁',
    birthDate: null,
    idNumber: '',
    address: '',
    settlementTypeId: settlementTypes.value[0]?.id || null,
    visitDate: dayjs().format('YYYY-MM-DD'),
    timePeriod: getDefaultTimePeriod(),
    departmentId: null,
    doctorId: null,
    registrationLevelId: registrationLevels.value[0]?.id || null,
    needMedicalRecord: 'Y',
    paymentType: '51', // 默认现金
    registrationTime: null,
    registrarId: userStore.id, 
    visitStatus: 1
  }
}

// 表单验证
const validateForm = () => {
  const requiredFields = [
    { field: 'caseNumber', name: '病历号' },
    { field: 'patientName', name: '姓名' },
    { field: 'gender', name: '性别' },
    { field: 'age', name: '年龄' },
    { field: 'ageType', name: '年龄类型' },
    { field: 'settlementTypeId', name: '结算类别' },
    { field: 'visitDate', name: '看诊日期' },
    { field: 'timePeriod', name: '午别' },
    { field: 'departmentId', name: '挂号科室' },
    { field: 'registrationLevelId', name: '号别' },
    { field: 'doctorId', name: '看诊医生' },
    { field: 'paymentType', name: '收费方式' }
  ]
  
  for (const { field, name } of requiredFields) {
    if (!formData.value[field]) {
      ElMessage.warning(`请填写${name}`)
      return false
    }
  }
  
  if (formData.value.idNumber && !validateIDNumber(formData.value.idNumber)) {
    ElMessage.warning('请输入有效的身份证号码')
    return false
  }
  
  if (formData.value.age && isNaN(Number(formData.value.age))) {
    ElMessage.warning('请输入有效的年龄')
    return false
  }
  
  return true
}

// 身份证号验证
const validateIDNumber = (idNumber) => {
  return /(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(idNumber)
}

// 根据科室选择医生
const handleDepartmentChange = async () => {
  try {
    if (!formData.value.departmentId) {
      doctors.value = []
      formData.value.doctorId = null
      return
    }
    
    const response = await service.get(`/user/getByDeptId?deptId=${formData.value.departmentId}`)
    console.log('原始医生数据:', response)  // 调试用
    
    // 修正字段映射 - 注意字段名必须与响应数据完全一致
    doctors.value = (response.data || response).map(doctor => ({
      id: doctor.id,
      realName: doctor.realName  // 确保使用后端返回的准确字段名
    }))
    
    console.log('处理后的医生数据:', doctors.value)  // 调试用
    
    formData.value.doctorId = doctors.value.length === 1 ? doctors.value[0].id : null
    
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败: ' + (error.message || '请稍后重试'))
    doctors.value = []
    formData.value.doctorId = null
  }
}

// 计算年龄
const calculateAge = () => {
  if (!formData.value.birthDate) return
  
  const birthdate = new Date(formData.value.birthDate)
  const today = new Date()
  const timeDiff = today - birthdate
  const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
  const monthsDiff = Math.floor(daysDiff / 30.44)
  let yearsDiff = today.getFullYear() - birthdate.getFullYear()
  
  const monthCheck = today.getMonth() - birthdate.getMonth()
  if (monthCheck < 0 || (monthCheck === 0 && today.getDate() < birthdate.getDate())) {
    yearsDiff--
  }
  
  if (yearsDiff >= 2) {
    formData.value.age = yearsDiff
    formData.value.ageType = '岁'
  } else if (monthsDiff >= 1) {
    formData.value.age = monthsDiff
    formData.value.ageType = '月'
  } else {
    formData.value.age = daysDiff
    formData.value.ageType = '天'
  }
}

// 看诊日期选择处理
const handleVisitDateChange = () => {
  if (!formData.value.visitDate) return
  
  const today = dayjs().format('YYYY-MM-DD')
  formData.value.timePeriod = formData.value.visitDate === today 
    ? getDefaultTimePeriod() 
    : '上午'
  
  checkDoctorSchedule()
}

// 午别变化处理
const handleTimePeriodChange = () => {
  checkDoctorSchedule()
}

// 挂号级别变化处理
const handleRegistrationLevelChange = () => {
  // 可能需要更新费用显示或其他相关信息
}

// 医生选择变化处理
const handleDoctorChange = () => {
  checkDoctorSchedule()
}

// 病历本选项变化处理
const handleMedicalRecordChange = () => {
  // 可能需要更新费用计算
}

// 检查医生排班
const checkDoctorSchedule = async () => {
  try {
    if (!formData.value.doctorId || !formData.value.visitDate) {
      return;
    }

    const response = await service.get(
      `/schedule/check?doctorId=${formData.value.doctorId}&date=${formData.value.visitDate}`
    );
    console.log('原始排班数据:', response);  // 调试用

    // 修正字段映射 - 注意字段名必须与响应数据完全一致
    const schedules = (response.data || response).map(schedule => ({
      id: schedule.id,
      timePeriod: schedule.timePeriod, // 确保使用后端返回的准确字段名
      // 其他需要的排班字段...
    }));
    console.log('处理后排班数据:', schedules);  // 调试用

    // 检查当前选择的时间段（上午/下午）
    const timePeriod = formData.value.timePeriod;
    const hasSchedule = schedules.some(schedule => 
      schedule.timePeriod === timePeriod
    );

    if (!hasSchedule) {
      // 获取所有可用时间段
      const availablePeriods = [...new Set(schedules.map(s => s.timePeriod))];
      ElMessage.warning(`该医生在${formData.value.visitDate} ${timePeriod}没有排班，可选时间段：${availablePeriods.join('、')}`);
      formData.value.doctorId = null;
    }
    
  } catch (error) {
    console.error('检查医生排班失败:', error);
    ElMessage.error('检查医生排班失败: ' + (error.message || '请稍后重试'));
    formData.value.doctorId = null;
  }
};

// 获取支付方式标签
const getPaymentTypeLabel = (typeValue) => {
  const type = paymentTypes.value.find(item => item.value === typeValue)
  return type ? type.label : typeValue
}

// 初始化数据
const initData = async () => {
  try {
    loading.value = true
    
    // 使用Promise.all并行请求，统一处理响应
    const [genderRes, deptRes,  settleRes, levelRes] = await Promise.all([
      service.get("/constantItem/getByTypeId?id=7"),
      service.get("/dept/list"),
      service.get("/settlementType/list"),
      service.get("/registrationLevel/list")
    ])
    
    // 按照常数管理页面的方式处理响应数据
    genderOptions.value = Array.isArray(genderRes) ? genderRes : []
    departments.value = Array.isArray(deptRes) ? deptRes : []
    settlementTypes.value = Array.isArray(settleRes) ? settleRes : []
    registrationLevels.value = Array.isArray(levelRes) ? levelRes : []
    
    // 设置默认值
    formData.value = {
      ...formData.value,
      settlementTypeId: settlementTypes.value[0]?.id || null,
      registrationLevelId: registrationLevels.value[0]?.id || null,
      paymentType: '51',
      departmentId: departments.value[0]?.id || null
    }
    
    // 如果有默认科室，自动加载医生
    if (formData.value.departmentId) {
      await handleDepartmentChange()
    }
    
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败: ' + (error.message || '请检查网络连接'))
  } finally {
    loading.value = false
  }
}

// 监听科室变化，重置医生选择
watch(() => formData.value.departmentId, () => {
  formData.value.doctorId = null
  doctors.value = []
})

onMounted(() => {
  initData()
  formData.value.caseNumber = generateCaseNumber()
})
</script>